﻿using InControls.Common;
using InControls.PLC;
using InControls.PLC.FX;
using PLCDEMO.test;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace PLCDEMO
{
    public partial class Form3 : Form
    {
        Random _Random = new Random();
        private FxSerialDeamon _FxSerial;
        private string cmd;
        FxCommandResponse res;
        private List<uint> send_count = new List<uint>();
        StringBuilder sb = new StringBuilder();
        private List<Thread> _threadList = new List<Thread>();
        bool rb_mode_status = false;
        public bool savePicFlag = false;
        //private Thread seeIO;
        public Form3()
        {
            InitializeComponent();
        }
        private void Form3_Load(object sender, EventArgs e)
        {
            this.SetDesktopLocation(800, 500);
            toolStripStatusLabel2.Text = "close";
            string[] str = SerialPort.GetPortNames();
            foreach (string s in str)
            {
                comboBox1.Items.Add(s);
            }

            cb_bit.Text = "M";
            tb_bit.Text = "0";
            tb_16.Text = "0";
            cb_16.Text = "D";
            comboBox1.Text = "com9";
            tb_16_send.Text = "0";
            tb_bit_send.Text = "0";
            this.rb_mode.Appearance = System.Windows.Forms.Appearance.Button;

        }


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (_FxSerial == null)
                {
                    string strSerialName = comboBox1.SelectedItem.ToString().TrimEnd();
                    string str = strSerialName.Substring(strSerialName.Length - 1, 1);
                    _FxSerial = new FxSerialDeamon();
                    if (_FxSerial.Start(int.Parse(str)) == true)
                    {
                        toolStripStatusLabel2.Text = "open susess!";
                        textBox1.Text += "\r\nopen susess  " + DateTime.Now.ToString();
                        MessageBox.Show("打开成功！");
                        pl_control.Enabled = true;
                        button1.Enabled = false;
                    }
                    else
                    {
                        textBox1.Text += "\r\nopen bad    " + DateTime.Now.ToString();
                        MessageBox.Show("打开失败！");
                        _FxSerial.Dispose();
                    }
                }

            }
            catch
            {
                MessageBox.Show("BAD");
                toolStripStatusLabel2.Text = "close";
                if (_FxSerial != null)
                {
                    _FxSerial.Dispose();
                }

            }

        }



        private void button2_Click(object sender, EventArgs e)
        {
            if (_FxSerial != null)
            {
                _FxSerial.Dispose();
            }
            _FxSerial = null;
            toolStripStatusLabel2.Text = "close";
            textBox1.Text += "\r\nclose sueesed    " + DateTime.Now.ToString();
            pl_control.Enabled = false;
            button1.Enabled = true;
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string str = cb_bit.SelectedItem.ToString() + tb_bit.Text;
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOn, new FxAddress(str, FxAddressLayoutType.AddressLayoutByte));
            textBox1.Text += str + "  " + DateTime.Now.ToString() + "\n";
            res = _FxSerial.Send(0, cmd);
            textBox1.Text += res.ToString() + "\r\n";
            Debug.WriteLine(res.ToString());
        }

        private void button4_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            string[] str = SerialPort.GetPortNames();
            foreach (string s in str)
            {
                comboBox1.Items.Add(s);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string str = cb_bit.SelectedItem.ToString() + tb_bit.Text;
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOff, new FxAddress(str, FxAddressLayoutType.AddressLayoutByte));
            textBox1.Text += cmd + "  " + DateTime.Now.ToString() + "\n";
            res = _FxSerial.Send(0, cmd);
            textBox1.Text += res.ToString() + "\n";
        }


        private void button6_Click(object sender, EventArgs e)
        {
            List<uint> lst = new List<uint>();
            //for (int k = 0; k < 10; k++)
            //    lst.Add((uint)_Random.Next());
            try
            {
                sb.Append(cb_16.Text);
                sb.Append(tb_16.Text);
            }
            catch (Exception s)
            {
                MessageBox.Show("数据不对");
                return;
            }
            //uint temp = uint.Parse(tb_16_send.Text, System.Globalization.NumberStyles.HexNumber);
            send_count.Add(uint.Parse(tb_16_send.Text, System.Globalization.NumberStyles.HexNumber));

            foreach (uint i in send_count)
            {
                lst.Add(i);// *256
            }

            cmd = FxCommandHelper.Make<UInt16DataType>(FxCommandConst.FxCmdWrite, new FxAddress(sb.ToString(), ControllerTypeConst.ctPLC_Fx), lst);
            //调试显示
            textBox1.Text += "\r\n" + cmd;
            res = _FxSerial.Send(0, cmd);
            textBox1.Text += "\r\n" + res;
            if (res.ResultCode == ResultCodeConst.rcSuccess)
            {
                MessageBox.Show("发送成功");

            }

            //数据缓存区删除
            sb.Clear();
            send_count.Clear();
            Debug.WriteLine(res.ToString());
            return;
        }

        private void cbb1_CheckedChanged(object sender, EventArgs e)
        {

            if (cbb1.Checked)
            {
                //timer1.Enabled = true;
                testClass tc = new testClass();
                //委托对象的指针对应上函数实体 搭载了一个函数
                tc.re_main = new testClass.refeshIO(ReadDData);
                //线程搭上了一个函数
                //mainRefresh 里面有委托的指针
                Thread testClassThread = new Thread(new ThreadStart(tc.mainRefresh));
                _threadList.Add(testClassThread);
                testClassThread.Start();
            }
            else
            {
                foreach (var t in _threadList)
                {
                    t.Abort();
                }
                _threadList.Clear();
            }
        }

        public void ReadDData()
        {
            if (cb_16.InvokeRequired || textBox1.InvokeRequired || textBox4.InvokeRequired)
            {
                //再次创建一个TestClass类的对象 
                testClass tc = new testClass();
                //为新对象的mainThread对象搭载方法 
                tc.re_main = new testClass.refeshIO(ReadDData);
                this.Invoke(tc.re_main, new object[] { });
            }

            StringBuilder sb1 = new StringBuilder();
            List<uint> lst = new List<uint>();
            try
            {
                sb1.Append(cb_16.Text);
                sb1.Append(tb_16.Text);
            }
            catch (Exception s)
            {
                MessageBox.Show("数据不对");
                return;
            }
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdRead, new FxAddress(sb.ToString(), ControllerTypeConst.ctPLC_Fx), 2);
            res = _FxSerial.Send(0, cmd, UInt16DataType.Default);
            textBox1.Text += "\n" + res;
            if (res.ResponseValue != null)
            {
                foreach (int i in res.ResponseValue)
                {
                    int temp = i;
                    textBox4.Text = String.Format("{0:X}", i);
                }
            }
            sb.Clear();

        }

        private void btn2_read(object sender, EventArgs e)
        {
            try
            {
                sb.Append(cb_16.Text);
                sb.Append(tb_16.Text);
            }
            catch (Exception s)
            {
                MessageBox.Show("数据不对");
                return;
            }
            //List<uint> lst = new List<uint>();
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdRead, new FxAddress(sb.ToString(), ControllerTypeConst.ctPLC_Fx), 2);
            res = _FxSerial.Send(0, cmd, UInt16DataType.Default);
            textBox1.Text += "\n" + res;
            if (res.ResponseValue != null)
            {

                foreach (int i in res.ResponseValue)
                {
                    int temp = i;
                    textBox4.Text = String.Format("{0:X}", i);// 
                }

            }
            sb.Clear();
        }


        private void btn_backward_MouseDown(object sender, MouseEventArgs e)
        {
            if (rb_mode_status == true) return;
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOn, new FxAddress("M0", FxAddressLayoutType.AddressLayoutByte));
            res = _FxSerial.Send(0, cmd);
        }
        private void btn_backward_MouseUp(object sender, MouseEventArgs e)
        {
            if (rb_mode_status == true) return;
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOff, new FxAddress("M0", FxAddressLayoutType.AddressLayoutByte));
            res = _FxSerial.Send(0, cmd);
        }

        private void btn_forward_MouseUp(object sender, MouseEventArgs e)
        {
            if (rb_mode_status == true) return;
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOff, new FxAddress("M1", FxAddressLayoutType.AddressLayoutByte));
            res = _FxSerial.Send(0, cmd);
        }

        private void btn_forward_MouseDown(object sender, MouseEventArgs e)
        {
            if (rb_mode_status == true) return;
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOn, new FxAddress("M1", FxAddressLayoutType.AddressLayoutByte));
            res = _FxSerial.Send(0, cmd);
        }


        private void rb_mode_Click(object sender, EventArgs e)
        {

            if (rb_mode_status == false)
            {

                rb_mode.Text = "寸动";
                rb_mode_status = true;
            }
            else
            {
                rb_mode.Text = "点动";
                rb_mode_status = false;
            }
        }

        private void tb_16_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsLetter(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void tb_16_send_KeyPress(object sender, KeyPressEventArgs e)
        {
            //分析 IndexOf查找在0123456789ABCDEF中 是否存在e.KeyChar的字符，没有的话就返回-1
            e.Handled = "0123456789ABCDEF \b\r\n".IndexOf(char.ToUpper(e.KeyChar)) < 0;
        }

        private void tb_bit_send_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar == '0') || (e.KeyChar == '1'))
            {
                //e.Handled = true;//为true时表示已经处理了事件（即不处理当前键盘事件  不接受）
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }


        private void tb_bit_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar))
            {
                //e.Handled = true;//为true时表示已经处理了事件（即不处理当前键盘事件  不接受）
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }

        }

        private void tb_pulls_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar))
            {
                //e.Handled = true;//为true时表示已经处理了事件（即不处理当前键盘事件  不接受）
                e.Handled = true;
            }
        }


        private void btn_run_Click(object sender, EventArgs e)
        {
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOn, new FxAddress("M10", FxAddressLayoutType.AddressLayoutByte));
            res = _FxSerial.Send(0, cmd);
            Thread.Sleep(50);

        }

        private void btn_back_Click(object sender, EventArgs e)
        {
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOn, new FxAddress("M11", FxAddressLayoutType.AddressLayoutByte));
            res = _FxSerial.Send(0, cmd);
            Thread.Sleep(50);

        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            cmd = FxCommandHelper.Make(FxCommandConst.FxCmdForceOn, new FxAddress("M3", FxAddressLayoutType.AddressLayoutByte));
            res = _FxSerial.Send(0, cmd);
            Thread.Sleep(50);

        }

        private void ccb_savePic_CheckedChanged(object sender, EventArgs e)
        {
            if (ccb_savePic.Checked)
            {
                savePicFlag = true;
            }
            else
            {
                savePicFlag = false;
            }
        }

        private void Form3_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.KeyChar = (Char)0;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            textBox1.SelectionStart = textBox1.Text.Length;
            textBox1.ScrollToCaret();
            if(textBox1.TextLength > 300)
            {
                string str = textBox1.Text.Substring(200, 100);
                textBox1.Text = str;
            }
        }
    }
}
